import {isMobile} from '../common/utils'
import {playerEvents} from './playerEvents'
import EventEmitter from '../common/EventEmitter'
import {flvCommon} from '../common/utils'
import '../common/styles/object.css'
export default class XchatPlayer{
	constructor(videoparam) {
		if(!videoparam){
			console.error("直播视频初始化参数必传!")
		}
	  if(isMobile){
			console.log('================启动h5全屏播放器====================')
			return import('./mobile/fullScreenPlayer').then(({default:fullScreenPlayer})=>{
				this.player = new fullScreenPlayer(videoparam)
				this.videoparam = videoparam
				this.init()
				return this
			})
		}else{
			if(flvCommon.pcflvSupport && videoparam.flv){
				console.log('===========启动pc FLV播放器===============')
				return import('./pc/dPlayer/DflvPlayer').then(({default:DflvPlayer})=>{
					this.player = new DflvPlayer(videoparam)
					this.videoparam = videoparam
					this.init()
					return this
				})
			}else{
				console.log('=============启动pc FLASH播放器===============')
				return import('./pc/flashPlayer/VideoSwf').then(({default:VideoSwf})=>{
					this.player = new VideoSwf(videoparam,videoparam.el,videoparam.type,videoparam.callbackFn)
					this.videoparam = videoparam
					this.init()
					return this
				})
			}
		}
	}
	init(){
		this.emitter = new EventEmitter()
		this.playerEvents = playerEvents
		this.eventHandler()
	}
	eventHandler(){
		this.player.on(this.playerEvents.NATIVE_PLAYER_PLAY,()=>{
			this.emitter.trigger(this.playerEvents.NATIVE_PLAYER_PLAY)
		})
		this.player.on(this.playerEvents.FLV_ERROR,()=>{
			if(isMobile){
				import('./mobile/fullScreenPlayer').then(({default:fullScreenPlayer})=>{
					this.videoparam = Object.assign(this.videoparam,{openHls:true})
					this.player = new fullScreenPlayer(this.videoparam)
				})
			}else{
				let flv_error_tip = '<div class="flv-error-tips" style="position: absolute;width:200px;top:50%;left:50%;transform: translate(-50%,-50%);font-size: 12px;color:#fff;background: #000;line-height: 33px;text-align: center;border-radius: 5px;white-space: nowrap;padding:0 10px;z-index:3;">当前flv无法播放,正在帮您切换,请稍等</div>'
				document.getElementById(this.videoparam.el).insertAdjacentHTML('beforeEnd', flv_error_tip)
				setTimeout(()=>{
					document.querySelector('.flv-error-tips').parentNode.removeChild(document.querySelector('.flv-error-tips'))
					import('./pc/flashPlayer/VideoSwf').then(({default:VideoSwf})=>{
						this.player = new VideoSwf(this.videoparam,this.videoparam.el,this.videoparam.type,this.videoparam.callbackFn)
					})
				},1000)
			}
			this.emitter.trigger(this.playerEvents.FLV_ERROR)
		})
		this.player.on(this.playerEvents.SET_PLAYER_INDEX,()=>{
			this.emitter.trigger(this.playerEvents.SET_PLAYER_INDEX)
		})
	}
	on(event, listener) {
		this.emitter.on(event, listener)
	}
	off(event, listener) {
		this.emitter.off(event, listener)
	}
	destroy(){
		if(this.player){
			this.player.destroy()
		}
	}
}